#include "MonsterClient.h"

#include <string>

#define MONSTER_IMAGE_HEIGHT 27.0
#define MONSTER_IMAGE_WIDTH 26.0

sf::Packet& operator >>(sf::Packet& packet, MonsterClient& monsterClient) {
	int dir;
	packet >> monsterClient.position.x >> monsterClient.position.y >> dir;

	monsterClient.direction = (characterDirection)dir;

	return packet;
}

MonsterClient::MonsterClient() {
	sequence = 0;
	direction = RIGHT;

	vitesseMove = sf::milliseconds(50);
	chronoTime.restart();
	vitesseMove = sf::milliseconds(50);

	/* Initialisation des matrices comboBox */
	sf::Vector2f matriceTemp[8] = {
		sf::Vector2f(3, 6),
		sf::Vector2f(35, 6),
		sf::Vector2f(67, 5),
		sf::Vector2f(99, 5),
		sf::Vector2f(131, 6),
		sf::Vector2f(163, 6),
		sf::Vector2f(195, 5),
		sf::Vector2f(227, 5)
	};
	memcpy(textureRunLeftSequence, matriceTemp, sizeof(sf::Vector2f) * 8);
	memcpy(textureRunRightSequence, matriceTemp, sizeof(sf::Vector2f) * 8);

	std::string path = "../Img/monster/";

	/* Texture du monstre marchant vers la droite */
	std::string filename = "run_right.png";	
	if (!monsterRunRight.loadFromFile(path + filename)) {
		printf("Erreur au chargement de la texture\n");
	}

	/* Texture du monstre marchant vers la gauche */
	filename = "run_left.png";	
	if (!monsterRunLeft.loadFromFile(path + filename)) {
		printf("Erreur au chargement de la texture\n");
	}
}

/* Dessine le monster dans la fenetre w */
void MonsterClient::draw(sf::RenderWindow& w) {
	if (direction == RIGHT) {
		monsterSprite.setTexture(monsterRunRight, true);
		monsterSprite.setTextureRect(sf::IntRect(textureRunRightSequence[sequence].x,
		textureRunRightSequence[sequence].y, MONSTER_IMAGE_WIDTH, MONSTER_IMAGE_HEIGHT));

	} else if (direction == LEFT) {
		monsterSprite.setTexture(monsterRunLeft, true);
		monsterSprite.setTextureRect(sf::IntRect(textureRunLeftSequence[sequence].x,
		textureRunRightSequence[sequence].y, MONSTER_IMAGE_WIDTH, MONSTER_IMAGE_HEIGHT));
	}

	/* Place le sprite a la position du monstre */
	monsterSprite.setOrigin(MONSTER_IMAGE_WIDTH/2, MONSTER_IMAGE_HEIGHT/2); // TODO changer ????????????????????
	monsterSprite.setPosition(position.x, position.y);

	w.draw(monsterSprite);
}


void MonsterClient::receive(sf::TcpSocket& socket) {
		sf::Packet packet;

		socket.receive(packet);
		packet >> *this;
}

void MonsterClient::animationMonster() {
	
	time = chronoTime.getElapsedTime();
		
	//Calcul du temps avant d'executer un nouveau deplacement
	if(time > vitesseMove) {
		incSequence();
		chronoTime.restart();
	}

}


void MonsterClient::incSequence() {
	sequence++;

	if (sequence == 8) {
		sequence = 0;
	}
}